<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="userInfo.query"
            clearable
            @clear="getList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
            ></el-button></el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="dialogVisible = true">添加用户</el-button></el-col
        >
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 这里的slot-scope="scope"拿的是上面el-table :data="userList"的数据 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210px" >
            <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="min" @click="editUser(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="min" @click="deleteUser(scope.row.id)"></el-button>
          <el-tooltip content="修改权限" effect="dark" placement="top">
            <el-button type="warning" icon="el-icon-setting" size="min" @click="allocRoleTo(scope.row)"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="修改用户信息" :visible.sync="editDialVisible" width="50%" @close="editClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialVisible= false">取 消</el-button>
        <el-button type="primary" @click="editUserTo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="allocRole" width="50%" @close="allocRoleClose">
      <div>
          <p>当前用户名：{{allocUserInfo.username}}</p>
          <p>当前的角色：{{allocUserInfo.role_name}}</p>
          <p>分配新角色：
              <el-select v-model="roleId" placeholder="请选择角色">
                  <el-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.roleName"></el-option>
              </el-select>
          </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocRole= false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加用户信息" :visible.sync="dialogVisible" width="50%" @close="addClose">
      <!-- <span>是否添加用户</span> -->
      <!-- ref用来重置 -->
      <el-form ref="addUserRef" :model="addUser" :rules="addUserRules" label-width="70px">
          <!-- prop用来指定校验规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username" ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserTo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
      var checkEmail=(rule,value,cb)=>{
          const rexRule=/^([a-zA-Z0-9-_])+@([a-zA-Z0-9-_])+(\.[a-zA-Z0-9-_])+/
          if(rexRule.test(value)) return cb()
            cb(new Error('请输入合法邮箱'))
    }
    return {
      userList: [],
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      addUser:{
          username:'',
          password:'',
          email:'',
          mobile:''
      },
      editForm:{

      },
      addUserRules:{
          username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 4, max: 9, message: '长度在 4到 9个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6到 15个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator:checkEmail,trigger:'blur'}
          ],
          phonenum: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
          ],
      },
      editFormRules:{
          username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 4, max: 9, message: '长度在 4到 9个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator:checkEmail,trigger:'blur'}
          ],
          phonenum: [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
          ],
      },
      total: 0,
      dialogVisible:false,
      editDialVisible:false,
      allocRole:false,
      allocUserInfo:{},
      roleList:[],
      roleId:''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      //一定要{params:this.userInfo}这么传参才行，直接传入userInfo会错误？why？
      const { data: res } = await this.$http.get('users', {
        params: this.userInfo,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      console.log(this.userList)
    },
    handleSizeChange(val) {
      this.userInfo.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.userInfo.pagenum = val
      this.getList()
    },
    async switchChange(val) {
      const { data: res } = await this.$http.put(
        `/users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status != 200) return this.$message.error('shibai')
      console.log(res)
    },
    addClose(){
        this.$refs.addUserRef.resetFields()
    },
    addUserTo(){
        this.$refs.addUserRef.validate(async vaild=>{
            if(!vaild) return
            //发起网络请求
            const {data:res}=await this.$http.post('users',this.addUser)
            if(res.meta.status!==201) this.$message.error('添加失败')
            this.$message.success('添加用户成功')
            this.dialogVisible=false
            this.getList()
        })
    },
    editClose(){
        this.$refs.editFormRef.resetFields()
    },
    editUserTo(){
        this.$refs.editFormRef.validate(async vaild=>{
            if(!vaild) return 
            const {data:res} =await this.$http.put('users/'+this.editForm.id,this.editForm)
            if(res.meta.status!=200) return this.$message.error("修改失败")
            this.editDialVisible=false
            this.getList()
            this.$message.success("修改成功")
        })
    },
    async editUser(val){
        console.log(val)
        const {data:res}=await this.$http.get('users/'+val.id)
        if(res.meta.status!==200) return this.$message.error('获取失败')
        this.editForm=res.data
        this.editDialVisible=true
    },
    async deleteUser(id){
        console.log(id)
        const confirmResult=await this.$confirm('你确定要删除该信息吗？','提示',{
            confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!='confirm') return this.$message.info("已取消删除")
        const {data:res}=await this.$http.delete('users/'+id)
        if(res.meta.status!=200) return this.$message.error("删除失败")
        this.$message.success("删除成功")
        this.getList()
    },
    async allocRoleTo(role){
        this.allocUserInfo=role
        const {data:res}=await this.$http.get('roles')
        if(res.meta.status!=200) return this.$message.error("错误")
        this.roleList=res.data
        this.allocRole=true
    },
    async saveRoleInfo(){
        if(!this.roleId) return this.$message.error("请选择要分配的角色")

        const {data:res}=await this.$http.put(`users/${this.allocUserInfo.id}/role`,{
            rid:this.roleId
        })
        if(res.meta.status!==200) return this.$message.error('更改失败')
        this.allocUserInfo=res.data
        this.$message.success(res.meta.msg)
        this.allocRole=false
    },
    allocRoleClose(){
        this.roleId=''
        this.roleList=[]
        this.getList()
    }
  },
}
</script>
<style lang="less" scoped>
</style>